package cn.bxshey.serviceModule.service.impl;

import cn.bxshey.commonModule.constant.RedisConstant;
import cn.bxshey.commonModule.enums.ResultEnum;
import cn.bxshey.commonModule.exception.BusinessException;
import cn.bxshey.commonModule.redis.RedisUtils;
import cn.bxshey.daoModule.mapper.DynamicMapper;
import cn.bxshey.dtoModule.dynamic.SelectPageDTO;
import cn.bxshey.entityModule.entity.Dynamic;
import cn.bxshey.serviceModule.service.DynamicService;
import cn.bxshey.voModule.dynamic.DetailVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 动态(Dynamic)表服务实现类
 *
 * @作者：不想说话而已
 * @Date：2024/3/9 18:46
 */
@Service("dynamicService")
public class DynamicServiceImpl extends ServiceImpl<DynamicMapper, Dynamic> implements DynamicService {

    @Resource
    DynamicMapper dynamicMapper;

    @Resource
    RedisUtils redisUtils;

    /**
     * 查询动态详情内容
     *
     * @param id 主键id
     * @return 单个动态详情内容
     */
    @Override
    public DetailVO selectById(Long id) {
        return dynamicMapper.selectById(id);
    }

    /**
     * 分页查询动态详情内容
     *
     * @param dto 分页查询参数
     * @return 多个动态详情内容
     */
    @Override
    public List<DetailVO> selectPageDTO(SelectPageDTO dto) {
        dto.setPage((dto.getPage() - 1) * dto.getSize());
        return dynamicMapper.selectPage(dto);
    }

    /**
     * 动态文章点赞
     *
     * @param id  动态文章id
     * @param uid 用户id
     * @return 点赞或取消点赞,true:点赞  false:取消点赞
     */
    @Override
    public Boolean updateSupport(Long id, Long uid) {

        //检查redis中是否已被点赞了
        Long bool = redisUtils.isListValue(RedisConstant.SUPPORT, uid, id);
        if (bool!=null && bool!=-1) {
            //表明，用户进行的是取消点赞操作
            redisUtils.delListValue(RedisConstant.SUPPORT, uid,id);
            return false;
        }
        //否则进行点赞操作
        try {
            redisUtils.addSetList(RedisConstant.SUPPORT, uid, id);
        } catch (Exception e) {
            throw new BusinessException(ResultEnum.ERROR_SUPPORT, e);
        }
        return true;
    }

    /**
     * 检查动态是否点赞
     * @param id 动态文章id
     * @param uid 用户id
     * @return true 为点赞  false 未点赞
     */
    @Override
    public Boolean isSupport(Long id, Long uid) {
        Long bool = redisUtils.isListValue(RedisConstant.SUPPORT, uid, id);
        return bool != null && bool != -1;
    }
}

